package org.linlinjava.litemall.core.util;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class TokenUtil {

    public static String getTokenValue(HttpServletRequest  request)  {
        String token = request.getHeader("Cookie");
        //sidebarStatus=0; JSESSIONID=f0613b8b-a136-48ec-88ce-051934f57584; X-Litemall-Admin-Token=f0613b8b-a136-48ec-88ce-051934f57584
        Map<String, String> tokenMap = parseTokenString(token);
        return tokenMap.getOrDefault("X-Litemall-Admin-Token", null);
    }


    public static Map<String, String> parseTokenString(String tokenString) {
        Map<String, String> tokenMap = new HashMap<>();
        if (tokenString == null || tokenString.isEmpty()) {
            return tokenMap;
        }

        // 去除字符串开头的 "//" 或其他不需要的部分
        if (tokenString.startsWith("//")) {
            tokenString = tokenString.substring(2);
        }

        // 按照分号分割字符串
        String[] keyValuePairs = tokenString.split(";");
        for (String pair : keyValuePairs) {
            String[] entry = pair.split("=");
            if (entry.length == 2) {
                String key = entry[0].trim();
                String value = entry[1].trim();
                tokenMap.put(key, value);
            }
        }

        return tokenMap;
    }

}
